<?php
/**
 * Created by PhpStorm.
 * FileName: AirwayController.class.php
 * User: Administrator
 * Date: 2018/9/11
 * Time: 16:59
 */

namespace Admin\Controller;

use Admin\Controller\AdminController;
use Admin\Model\AirwayDetailModel;
use Admin\Model\AirwayModel;
use Admin\Model\TripModel;
use Admin\Model\UserModel;

/**
 * Class AirwayController
 * @package Admin\Controller
 * @todo 航线管理模块
 * @menu 航线管理
 * @author fanyuliang
 * @menuAuto index
 * @order 500
 * @icon article.png
 */
class AirwayController extends AdminController {

    private $tripModel;
    private $airwayModel;
    private $airwayDetailModel;
    private $userModel;

    function __construct() {
        parent::__construct();
        $this->tripModel = new TripModel();
        $this->airwayModel = new AirwayModel();
        $this->airwayDetailModel = new AirwayDetailModel();
        $this->userModel = new UserModel();
    }

    /**
     * @todo 航线管理
     * @menu 航线列表
     * @order 2
     */
    public function index() {
        $this->setForm();
        $where = array();
        if(IS_POST){
            if(I('air_code') != ''){
                $where['air_code'] = I('air_code');
            }

            if(I('origin') != ''){
                $where['origin'] = I('origin');
            }

            if(I('destination') != ''){
                $where['destination'] = I('destination');
            }
        }
        $pageSize = 15;
        $data = $this->airwayModel->getList($where,$pageSize);
        $this->setPageData($data);
        $this->display();
    }

    /**
     * @todo 修改航班
     */
    public function editAir() {
        $airId = I('id');
        if (IS_POST) {
            $this->doSave($airId);
        }
        $row = null;
        if ($airId) {
            $row = $this->airwayModel->detail(array('id' => $airId));
        }
        $this->assign('row',$row);
        $this->assign('id',$airId);
        $this->display('edit_air');
    }

    /**
     * @todo 行程明细
     */
    public function listTrip() {
        $airId = I('airId');
        $where = array(
            'id' => $airId
        );
        $pageSize = 50;
        $data = $this->airwayModel->detail($where,$pageSize);
        $this->assign('listData',reset($data));
        $this->display('trip_list');
    }

    /**
     * @todo 行程管理
     * @menu 行程列表
     * @order 1
     */
    public function trip() {
        $this->setForm();
        $where = array();
        if(IS_POST){
            if(I('user_id')){
                $where['user_id'] = I('user_id');
            }
            if(I('ticket_id')){
                $where['ticket_id'] = array('like','%'.I('ticket_id').'%');
            }
            $trip_from_date = I('trip_from_date');
            $trip_to_date = I('trip_to_date');
            if ($trip_from_date && $trip_to_date) {
                $where['add_time'] = array('between',sprintf('%s,%s',strtotime(sprintf('%s 00:00:00',$trip_from_date)),strtotime(sprintf('%s 23:59:59',$trip_to_date))));
                $this->assign('trip_from_date',strtotime($trip_from_date));
                $this->assign('trip_to_date',strtotime($trip_to_date));
            } else if ($trip_from_date) {
                $where['add_time'] = array('egt',strtotime(sprintf('%s 00:00:00',$trip_from_date)));
                $this->assign('trip_from_date',strtotime($trip_from_date));
            } else if ($trip_to_date) {
                $where['add_time'] = array('elt',strtotime(sprintf('%s 23:59:59',$trip_to_date)));
                $this->assign('trip_to_date',strtotime($trip_to_date));
            }
            if(I('state') != ''){
                $where['state'] = I('state');
            }
        }
        $pageSize = 15;
        $data = $this->tripModel->getList($where,$pageSize);
        $this->setPageData($data);
        if ($where['user_id']) {
            $searchUserName = $this->userModel->where(array('id' => $where['user_id']))->getField('real_name');
            $this->assign('searchUserName',$searchUserName);
        }
        $this->display();
    }

    /**
     * @todo 添加航班
     */
    public function setAir() {
        $tripId = I('tripId');
        if (IS_POST) {
            $this->doSave($tripId);
        }
        $rows = null;
        if ($tripId) {
            $rows = $this->airwayModel->detail(array('trip_id' => $tripId));
            $trip = $this->tripModel->detail(array('id' => $tripId));

        }
        $this->assign('rows',$rows);
        $this->assign('tripRow',$trip);
        $this->assign('tripId',$tripId);
        $this->display('set_air');
    }

    /**
     * @todo 查看航班
     */
    public function queryAir() {
        $tripId = I('tripId');
        $rows = null;
        if ($tripId) {
            $rows = $this->airwayModel->detail(array('trip_id' => $tripId));
            $trip = $this->tripModel->detail(array('id' => $tripId));

        }
        $this->assign('rows',$rows);
        $this->assign('tripRow',$trip);
        $this->assign('tripId',$tripId);
        $this->display('query_air');
    }

    /**
     * 设置航班信息
     */
    protected function doSave() {
        $response = array('status' => false, 'msg' => '航班信息保存失败!');
        $originData = $_POST;
        $tripId = $originData['tripId'];
        $air_code = $originData['air_code'];
        $origin = $originData['origin'];
        $destination = $originData['destination'];
        $depart_date = $originData['depart_date'];
        $reach_date = $originData['reach_date'];
        $dataList = array();
        $station = array();
        foreach ($air_code as $key => $item) {
            $data = array();
            $data['trip_id'] = $tripId;
            $data['air_code'] = $item;
            $data['origin'] = $origin[$key];
            $data['destination'] = $destination[$key];
            $data['depart_date'] = strtotime($depart_date[$key]);
            $data['reach_date'] = strtotime($reach_date[$key]);
            $data['add_time'] = time();
            $dataList[] = $data;
            $station[] = $origin[$key];
            $station[] = $destination[$key];
        }
        $this->airwayModel->remove(array('trip_id' => $tripId));
        $rs = $this->airwayModel->addAll($dataList);
        if ($rs !== false) {
            // 更新行程列表中的出发和到达时间
            $firstAir = reset($dataList);
            $endAir = end($dataList);
            $station = array_unique($station);
            if ($firstAir['origin'] == $endAir['destination']) {
                $station_rev = $station;
                $station_rev[] = $firstAir['origin'];
                unset($station_rev[0]);
            }
            $tripData = array(
                'origin' => $firstAir['origin'],
                'destination' => $endAir['destination'],
                'depart_date' => $firstAir['depart_date'],
                'reach_date' => $endAir['reach_date'],
                'station' => implode(',',$station),
                'station_rev' => implode(',',$station_rev),
                'station_num' => count($station)-1
            );
            $this->tripModel->update($tripData,array('id' => $tripId));
            $response['status'] = true;
            $response['msg'] = '航班信息保存成功!';
        }
        $this->ajaxReturn($response);
    }

    /**
     * 设置航班途径地
     * @param $airId
     * @param $names
     * @param $reach_dates
     * @return bool|mixed|string
     */
    private function handAirwayDetail($airId,$names,$reach_dates) {
        $airwayDetailData = array();
        foreach ($names as $key => $_name) {
            if (!$_name || !$reach_dates[$key]) {
                continue;
            }
            $airwayDetailData[] = array(
                'name' => $_name,
                'reach_date' => $reach_dates[$key]
            );
        }
        return $this->airwayDetailModel->add($airwayDetailData,$airId);
    }

    // 修改行程状态
    public function setTripStatus() {
        $response = array('status' => false, 'msg' => '行程状态修改失败!');
        $tripId = $_POST['id'];
        $statusId = $_POST['statusId'];
        $remark = $_POST['remark'];
        $data = array('status' => $statusId);
        if ($remark) {
            $data['remark'] = $remark;
        }
        if ($statusId == 1) {
            // 检查是否有航班信息
            $airs = $this->airwayModel->where(array('trip_id' => $tripId))->count();
            if ($airs > 0) {
                $this->tripModel->update($data,array('id' => $tripId));
                // 审核通过，开始接单
                $this->tripModel->update(array('state' => 1),array('id' => $tripId));
                $response['status'] = true;
                $response['msg'] = '行程状态修改成功!';
            } else {
                $response['msg'] = '无效的操作，请先设置该行程的航班信息!';
            }
        } else {
            $rs = $this->tripModel->update($data,array('id' => $tripId));
            if ($rs !== false) {
                if ($statusId == 2) {
                    // 审核未通过时，关闭行程
                    $this->tripModel->update(array('state' => 5),array('id' => $tripId));
                }
                $response['status'] = true;
                $response['msg'] = '行程状态修改成功!';
            }
        }
        $this->ajaxReturn($response);
    }

}